var base_filepath = ''
/** 
 * 上传文件接口
 */
function mergeImg() {
  var formData = new FormData();

  formData.append("file", $("#upload")[0].files[0]);
  formData.append("base_filepath", base_filepath)
  $("#layout").show();
  $.ajax({
    type: "POST",
    url: "/zyw/file/merge/uploading",
    data: formData,
    processData: false,
    contentType: false,
    success: function (res) {
      console.log(res)
      var bgsrc = "../images/face/bg" + res.randomindex + ".png";
      console.log(bgsrc)
      var facebg = document.getElementById("facebg")
      facebg.src = bgsrc
      $("#facebg").show()
      $("#outerborder").show()
      $("#target")[0].src = "data:image/png;base64," + res.result
      $("#example").hide();
      $("#layout").hide();
      $("#target").show();
      $("#share").show()
      var changebutton = document.getElementById("buildphoto");
      changebutton.innerHTML = '换个背景'
      Toast('点击“换个背景”，换种风格 ~', 3000)
    },
    error: function (res) {
      console.log(res)
      var status = res.status
      switch (status) {
        case 400:
          Toast('抱歉，上传的图片人脸不符合要求，请重新上传', 1000)
          break;
        case 500:
          Toast('抱歉，网络异常，请重新生成', 1000)
          break;
        default:
          break;
      }
      $("#layout").hide();
    }
  });
}

function getObjectURL(file) {
  var url = null;
  if (window.createObjectURL != undefined) { // basic
    url = window.createObjectURL(file);
  } else if (window.URL != undefined) { // mozilla(firefox)
    url = window.URL.createObjectURL(file);
  } else if (window.webkitURL != undefined) { // webkit or chrome
    url = window.webkitURL.createObjectURL(file);
  }
  return url;
}




$(".a-upload").on("change", "input[type='file']", function () {
  var filePath = $(this).val();
  var arr = filePath.split('\\');
  var fileName = arr[arr.length - 1];
  $(".showFileName").html(fileName);
  $('.appIcon').attr('src', getObjectURL($(this)[0].files[0]));
  // 调用函数，对图片进行压缩
  var path = getObjectURL($(this)[0].files[0])
  dealImage(path, {
    width: 1000
  }, function (base) {
    console.log(base)
    base_filepath = base
    Toast('图片上传成功，请点击“生成照片”', 3000)
    var changebutton = document.getElementById("buildphoto");
    changebutton.innerHTML = '生成照片'
    $("#buildphoto").show()
  });
})

function Toast(msg, duration) {
  duration = isNaN(duration) ? 3000 : duration;
  var m = document.createElement('div');
  m.innerHTML = msg;
  m.style.cssText = "max-width:60%;min-width: 150px;padding:0 14px;height: 80px;color: rgb(255, 255, 255);line-height: 80px;text-align: center;border-radius: 4px;position: fixed;top: 50%;left: 50%;border-radius:8px;transform: translate(-50%, -50%);z-index: 999999;background: rgba(0, 0, 0,.7);font-size: 26px;";
  document.body.appendChild(m);
  setTimeout(function () {
    var d = 0.5;
    m.style.webkitTransition = '-webkit-transform ' + d + 's ease-in, opacity ' + d + 's ease-in';
    m.style.opacity = '0';
    setTimeout(function () {
      document.body.removeChild(m)
    }, d * 1000);
  }, duration);
}

function share() {
  return new Promise(resolve => {
    var randomindex = Math.floor(Math.random() * 8) + 1
    var word = "/images/title" + randomindex + ".png"
    let mulitImg = [
      '../images/border.png',
      '../images/code.png',
      '../images/slogan.png',
      word
    ];
    let promiseAll = [],
      mimg = [],
      imgTotal = mulitImg.length;
    for (let i = 0; i < imgTotal; i++) {
      promiseAll[i] = new Promise((resolve, reject) => {
        mimg[i] = new Image()
        mimg[i].src = mulitImg[i]
        mimg[i].onload = function () {
          //第i张加载完成
          resolve(mimg[i])
        }
      })
    }
    Promise.all(promiseAll).then((mimg) => {
      var c = document.getElementById("myCanvas");
      var cw = $("#myCanvas").width()
      var ch = $("#myCanvas").height()
      var ctx = c.getContext("2d");
      //换脸图片
      var img = document.getElementById("target");
      var percent = 1
      var imgW = $("#myCanvas").width() * percent
      var border_img = new Image()
      border_img.src = '../images/border.png'
      //分享二维码
      // var qr_code = new Image()
      // qr_code.src = "../images/code.png"
      var qr_code = document.getElementById("qr_code");
      //底部字
      // var slogan = new Image()
      // slogan.src = "../images/slogan.png"
      var slogan = document.getElementById("slogan")
      //左上角字
      var u = navigator.userAgent;
      var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
      var wordpic = document.getElementById("wordpic")
      console.log(isiOS)
      if (!isiOS) {
        wordpic.src = word
      }

      ctx.drawImage(img, 0, 0, 800, 1200);
      // ctx.drawImage(img, (cw - imgW) / 2, 0, imgW, imgH);
      ctx.drawImage(qr_code, (cw - 60) / 2, 1000, 60, 60);
      ctx.drawImage(slogan, 200, 1100, 400, 20)
      ctx.drawImage(wordpic, 0, 0, 200, 400)
      // ctx.font = "30px A=rial";
      // ctx.fillText("致/敬/中/国/人/民/解/放/军", 400, 1100);
      // $("#myCanvas").show()
      $("#createface").hide()
      $("#sharemodal").show()
      let imageurl = c.toDataURL('image/png')
      resolve(imageurl)
    })



  })

}

async function solveshare() {
  try {
    let imageurl = await share()
    console.log(imageurl)
    let dataImg = document.getElementById("canvas_toimage")
    try {
      dataImg.src = imageurl
    } catch (e) {
      console.log(e);
    }
    $("#canvas_toimage").show()
    let urlImg = dataImg.src //urlImg为img路径
    console.log(urlImg)
  } catch (error) {
    console.log(error)
  }
}


// Get the modal
var modal = document.getElementById('myModal');


// When the user clicks anywhere outside of the modal, close it
window.onclick = function (event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}
window.onload = function (param) {
  $("#layout").hide();

  $("#man_button").on("click", function () {
    modal.style.display = "none";
    $.ajax({
      type: "GET",
      url: "/zyw/test?sex=1",
      success: function (res) {}
    });
  })
  $("#woman_button").on("click", function () {
    // var examplesrc = document.getElementById("example")
    // examplesrc.src = "/images/example.png"
    $.ajax({
      type: "GET",
      url: "/zyw/test?sex=2",
      success: function (res) {}
    });
    modal.style.display = "none";
  })

  $(".close_button").on("click", function (param) {
    $("#sharemodal").hide()
    $("#createface").show()
  })
}

/**
 * 图片压缩，默认同比例压缩
 * @param {Object} path
 * pc端传入的路径可以为相对路径，但是在移动端上必须传入的路径是照相图片储存的绝对路径
 * @param {Object} obj
 * obj 对象 有 width， height， quality(0-1)
 * @param {Object} callback
 * 回调函数有一个参数，base64的字符串数据
 */
function dealImage(path, obj, callback) {
  var img = new Image();
  img.src = path;
  img.onload = function () {
    var that = this;
    // 默认按比例压缩
    var w = that.width,
      h = that.height,
      scale = w / h;
    w = obj.width || w;
    h = obj.height || (w / scale);
    var quality = 0.7; // 默认图片质量为0.7
    //生成canvas
    var canvas = document.createElement('canvas');
    var ctx = canvas.getContext('2d');
    // 创建属性节点
    var anw = document.createAttribute("width");
    anw.nodeValue = w;
    var anh = document.createAttribute("height");
    anh.nodeValue = h;
    canvas.setAttributeNode(anw);
    canvas.setAttributeNode(anh);
    ctx.drawImage(that, 0, 0, w, h);
    // 图像质量
    if (obj.quality && obj.quality <= 1 && obj.quality > 0) {
      quality = obj.quality;
    }
    // quality值越小，所绘制出的图像越模糊
    var base64 = canvas.toDataURL('image/jpeg', quality);
    // 回调函数返回base64的值
    callback(base64);
  }
}